import { transIntToHex4Str } from "./dataUtils";
import { encryptByCBC, decryptByCBC } from "../pages/admin/jiami";
import { createNewDateThree } from "./adminUtils";
import { uploadFileNetworking } from "../api";
import { isNoBulbDevice } from "./pidUtils";
import { meshLog ,SPRemove,SPGet,SPSet } from "../config";

//下载profile
export const profileDataDownload = (value) => {
    let jiaminInfo = value.data
    jiaminInfo = jiaminInfo.replace(/\s*/g, "")
    let jie = JSON.parse(decryptByCBC(jiaminInfo))//解密之后的json
    meshLog("profileUtils.jsx,13行,解密之后所有的信息", jie);
    let mAreaSet = getAreaSetData(jie.groups, jie.groupExtends);
    let mGroupSet = getGroupSetData(jie.groups, jie.groupExtends);
    let mDeviceSet = getDeviceSetData(jie.nodes, jie.devices, jie.version);
    let mNoBulbSet = getNoBulbSetData(jie.nodes, jie.version);
    //新建数据结构
    createNewDateThree(mAreaSet, mGroupSet, mDeviceSet)
    //排序
    jie.scenes = sortAscData(jie.scenes);
    jie.schedules = sortAscData(jie.schedules);
    // //存储数据
    SPSet('noBulbSetx', JSON.stringify(mNoBulbSet))
    SPSet('sensorSetx', JSON.stringify(jie.sensors))
    SPSet('scenesSetx', JSON.stringify(jie.scenes))
    SPSet('smartshiftSetx', JSON.stringify(jie.smartShift))
    SPSet('scheduleSetx', JSON.stringify(jie.schedules))
    SPSet('deviceSetDefault', JSON.stringify(mDeviceSet))
    SPSet('RabProfile', JSON.stringify(jie))
    syncSmartshiftTimerData();
    return jie;
}
//上传profile
export const profileDataUpload = () => {
    let jie = JSON.parse(SPGet("RabProfile"));
    jie.smartShift = JSON.parse(SPGet("smartshiftSetx"));
    jie.schedules = JSON.parse(SPGet("scheduleSetx"));
    jie.isEmergency = SPGet("emergencyMode");
    meshLog("profileUtils.jsx,40行,wjk Profile Upload =", jie);
    let str = JSON.stringify(jie);
    let info = encryptByCBC(str)//加密之后的数据
    // meshLog("wjk Profile info =",info.length,'  ',info);
    uploadFileNetworking(info);
}
//获取DeviceNo，用于上传profile
export const saveDeviceNo = (jie) => {
    try {
        let siteInfo = jie.siteInfo;
        let provisioners = siteInfo.provisioners;
        for (let i = 0; i < provisioners.length; i++) {
            if (i == 0) {
                SPSet('deviceNo', provisioners[0].provisionUUID);
            }
        }
    } catch (resaon) {
        meshLog('profileUtils.jsx,57行,', resaon);
    }
}
//兼容V1-areaSet
export const getAreaSetData = (groups, groupExtends) => {
    let arrA = getGroupDataArr(groups, groupExtends, true);
    meshLog("profileUtils.jsx,63行,wjk profile AreaSet:", arrA);
    return arrA;
}
//兼容V1-groupSet
function getGroupSetData(groups, groupExtends) {
    let arrG = [];
    let arr = getGroupDataArr(groups, groupExtends, false);
    for (let i = 0; i < arr.length; i++) {
        let areaStr = arr[i].areaNo.substring(0, arr[i].areaNo.length - 1) + '0';
        arrG[i] = { 'areaNo': areaStr, 'groupNo': arr[i].areaNo, 'name': arr[i].name, 'minTrim': arr[i].minTrim, 'maxTrim': arr[i].maxTrim }
    }
    meshLog("profileUtils.jsx,74行,wjk profile GroupSet:", arrG);
    return arrG;
}
//兼容V1-deviceSet
export const getDeviceSetData = (nodes, devices, version) => {
    let arrD = [];
    let countD = 0;
    for (let i = 0; i < nodes.length; i++) {
        if (!nodes[i].hasOwnProperty('macAddress') || !nodes[i].hasOwnProperty('pid')) {
            continue;
        }
        if (typeof (nodes[i].pid) == 'undefined' || nodes[i].pid.length < 4) {
            continue;
        }
        let mAddr = nodes[i].unicastAddress;
        let mMin = '0000';
        let mMax = 'FFFF';
        let mSsidName = '';
        let mNanoWifiVer = '';
        let mlightID = 0;
        for (let j = 0; j < devices.length; j++) {
            if (parseInt(mAddr, 16) == devices[j].address) {
                mMin = transIntToHex4Str(devices[j].lightnessRange.minTrim);
                mMax = transIntToHex4Str(devices[j].lightnessRange.maxTrim);
                if (devices[j].hasOwnProperty('noLightDevice')) {
                    mSsidName = devices[j].noLightDevice.ssidName;
                    mNanoWifiVer = devices[j].noLightDevice.wifiVersion;
                }
                mlightID = devices[j].lightID;
            }
        }
        let mAreaNo = 'C000';
        let mGroupNo = '0000';
        let nAddr = getNodeAreas(nodes[i], version);
        // meshLog("wjk --- nAddr:",nAddr);
        for (let m = 0; m < nAddr.length; m++) {
            let str = nAddr[m];
            if (str.length == 4 && str.substring(str.length - 1, str.length) == '0') {
                mAreaNo = str;
            }
            if (str.length == 4 && str.substring(str.length - 1, str.length) != '0') {
                mGroupNo = str;
            }
        }
        arrD[countD] = {
            'address': mAddr, 'groupNo': mGroupNo, 'areaNo': mAreaNo, 'minTrim': mMin, 'maxTrim': mMax,
            'vid': nodes[i].vid, 'pid': nodes[i].pid, 'mac': nodes[i].macAddress, 'name': nodes[i].name,
            'nanoWifiVer': mNanoWifiVer, 'ssid': mSsidName,
            'powerIndex': '', 'tempIndex': '', 'maxPower': '', 'startingVoltage': '', 'lightID': mlightID
        };
        countD++;
    }
    meshLog("profileUtils.jsx,126行,wjk profile DeviceSet:", arrD);
    return arrD;
}
//兼容V1-NoBulbSet
function getNoBulbSetData(nodes, version) {
    let arr = [];
    let count = 0;
    for (let i = 0; i < nodes.length; i++) {
        if (isNoBulbDevice(nodes[i].pid)) {
            let mAddr = nodes[i].unicastAddress;
            let nAddr = getNodeAreas(nodes[i], version);
            arr[count] = { 'pid': nodes[i].pid, 'address': mAddr, 'areas': nAddr }
            count++;
        }
    }
    meshLog("profileUtils.jsx,141行,wjk profile NoBulb:", arr);
    return arr;
}
//保存新SmartshiftSet
export const saveDataSmartshiftSet = (smartType, scheType, isScheOnOff) => {
    let smartshiftSet = JSON.parse(SPGet("smartshiftSetx"));
    smartshiftSet.smartType = smartType;
    smartshiftSet.scheType = scheType;
    if (!isScheOnOff) {
        for (let i = 0; i < smartshiftSet.areaSet.length; i++) {
            smartshiftSet.areaSet[i].action = smartType;
        }
    }
    SPSet('smartshiftSetx', JSON.stringify(smartshiftSet))
    meshLog("profileUtils.jsx,155行,wjk profile SmartshiftSet:", smartshiftSet);
    profileDataUpload();
}
function syncSmartshiftTimerData() {
    let smartshiftSet = JSON.parse(SPGet("smartshiftSetx"));
    meshLog("profileUtils.jsx,160行,wjk isSync=", smartshiftSet.smartType);
    if (smartshiftSet.smartType > 0) {
        SPSet("syncTimer", "false");
    } else {
        SPSet("syncTimer", "true");
    }
}
//保存新SmartshiftSet
export const saveDataSmartshiftByAction = (areaNo, action) => {
    let smartshiftSet = JSON.parse(SPGet("smartshiftSetx"));
    for (let i = 0; i < smartshiftSet.areaSet.length; i++) {
        if (smartshiftSet.areaSet[i].address == areaNo) {
            smartshiftSet.areaSet[i].action = action;
        }
    }
    let mAction = 0;
    for (let i = 0; i < smartshiftSet.areaSet.length; i++) {
        if (smartshiftSet.areaSet[i].action == 1 && mAction <= 1) {
            mAction = 1;
        }
        if (smartshiftSet.areaSet[i].action == 2 && mAction <= 2) {
            mAction = 2;
        }
    }
    smartshiftSet.smartType = mAction;
    SPSet('smartshiftSetx', JSON.stringify(smartshiftSet))
    meshLog("profileUtils.jsx,186行,wjk profile SmartshiftSet:", smartshiftSet);
}
//保存新ScheduleSet
export const saveDataScheduleSet = (scheItem, isApply) => {
    meshLog("profileUtils.jsx,190行,wjk scheItem:", scheItem);
    let arrShe = JSON.parse(SPGet("scheduleSetx"));
    for (let i = 0; i < arrShe.length; i++) {
        if (arrShe[i].scheduleID == scheItem.scheduleID) {
            arrShe[i].isApply = isApply;
        }
    }
    SPSet('scheduleSetx', JSON.stringify(arrShe))
    meshLog("profileUtils.jsx,198行,wjk profile ScheduleSet:", arrShe);
    profileDataUpload();
}
function getGroupDataArr(groups, groupExtends, isArea) {
    // meshLog("wjk profile groups:",groups);
    // meshLog("wjk profile groupExtends:",groupExtends);
    let arr = [];
    let count = 0;
    for (let i = 0; i < groups.length; i++) {
        let str = groups[i].address;
        if (str == 'C000') {
            continue;
        }
        if (isArea && str.substring(str.length - 1, str.length) != '0') {
            continue;
        } else if (!isArea && str.substring(str.length - 1, str.length) == '0') {
            continue;
        }
        let mMin = '0000';
        let mMax = 'FFFF';
        for (let j = 0; j < groupExtends.length; j++) {
            if (parseInt(str, 16) == groupExtends[j].address) {
                mMin = transIntToHex4Str(groupExtends[j].lightnessRange.minTrim);
                mMax = transIntToHex4Str(groupExtends[j].lightnessRange.maxTrim);
            }
        }
        arr[count] = { 'areaNo': str, 'name': groups[i].name, 'minTrim': mMin, 'maxTrim': mMax }
        count++;
    }
    return arr;
}
function getNodeAreas(node, version) {
    let nAddr = [];
    let nCount = 0;
    if (version == '2.0.1' && node.hasOwnProperty('elements')) {
        let elements = node.elements;
        for (let m = 0; m < elements.length; m++) {
            for (let n = 0; n < elements[m].models.length; n++) {
                if (!elements[m].models[n].hasOwnProperty('subscribe') || elements[m].models[n].subscribe.length == 0) {
                    continue;
                }
                else {
                    for (let k = 0; k < elements[m].models[n].subscribe.length; k++) {
                        let str = elements[m].models[n].subscribe[k];
                        if (str.length > 0) {
                            nAddr[nCount] = str;   //16进制string
                            nCount++;
                        }
                    }
                }
            }
        }
    } else if (version == '2.0.2' && node.hasOwnProperty('groups')) {
        let groups = node.groups;
        for (let m = 0; m < groups.length; m++) {
            let str = transIntToHex4Str(groups[m]);
            nAddr[nCount] = str;  //10进制，需要转换为16进制string
            nCount++;
        }
    }
    return nAddr;
}
//排序
export const sortAscData = (lists) => {
    if (lists.length > 0) {
        return sortAscUtil(lists);
    } else {
        return lists;
    }
}
function sortAscUtil(lists) {
    return [...lists].sort((a, b) =>
        a.name > b.name ? 1 : -1,
    );
}
